﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Windows.Controls.Ribbon;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace serva
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public string path_Empresa = "";

		private Brush white = new SolidColorBrush(Colors.White);

        public Brush MainBrush
        {
            get { return white; }
            set { white = value; }
        }

		private Brush blue = new SolidColorBrush(Color.FromRgb(0x00, 0x7C, 0xEF));

        public Brush SecondaryBrush
        {
            get { return blue; }
            set { blue = value; }
        }

        
        /// <____OJO___>
        /// varigales globales para guardar
        /// </summary>
        /// 
        List<Unidad> Unidades = new List<Unidad>();
        Empresa empresa = new Empresa();
        List<Componente> inventario = new List<Componente>();


        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            empresa.Servicios.Add(new Servicio(){Nombre = "Servicio1"});
            Servicio s = new Servicio() { Nombre = "Servicio2"};
            s.listSub.Add(new Servicio() { Nombre = "subServicio1" });
            s.listSub.Add(new Servicio() {Nombre = "subServicio2"});
			Servicio s2 = new Servicio() { Nombre = "subServicio3"};
			s2.listSub.Add(new Servicio() { Nombre = "otro subservicio y algunas otras cosas que pueden pasar" });
			empresa.Servicios[0].listSub.Add(s2);
            empresa.Servicios.Add(s);
            CreateTree(empresa);
        }


        /// <summary>
        /// Crea el arbol visual, que muestra los servicios prestados 
        /// por esta empresa
        /// </summary>
        /// <param name="empresa"> La empresa que se usará de base para crear el arbol visual </param>
        private void CreateTree(Empresa empresa)
        {
            if(empresa.Servicios.Count == 0)
            {
                global::System.Windows.Forms.MessageBox.Show("¿Aun no ha ofrecido ningun servicio?");
                return;
            }

			int i = 0;
            arbol.Items.Clear();
            foreach (Servicio servicio in empresa.Servicios)
            {				
                arbol.Items.Add(SubTree(servicio, i));
				i ++;
            }
        }

        /// <summary>
        /// Crea un arbol visual, basandose en un servicio especificado
        /// </summary>
        /// <param name="servicio">El servicio que se toma como base para crear el arbol</param>
        /// <returns>El arbol creado</returns>
        TreeViewItem SubTree(Servicio servicio, int mode)
        {
			int i = 0;
            TreeViewItem item = new TreeViewItem();
            item.Header = servicio.Nombre;
			
            foreach (Servicio subServ in servicio.listSub)
            {
                item.Items.Add(SubTree(subServ, i));
				i++;
            }
			if(mode % 2 == 0)
			{
				item.Style = (Style)Application.Current.Resources["WhiteTreeItem"];
				item.Foreground = blue;
			}
			else
			{
				item.Style = (Style)Application.Current.Resources["BlueTreeItem"];
				item.Foreground = white;
			}
	
            item.Tag = servicio;
            return item;
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            Panel_Inventario panel = new Panel_Inventario();
            panel.ListUnidades = Unidades;
            //panel.ListInventario = empresa.Items;
            panel.ListInventario = inventario;
            panel.VerticalAlignment = VerticalAlignment.Stretch;
            panel.HorizontalAlignment = HorizontalAlignment.Stretch;
            grid.Child = panel;
            panel.Cargar();
        }



        private void MenuItem_Click1(object sender, RoutedEventArgs e)
        {
            Panel_Unidades panel = new Panel_Unidades();
            panel.ListUnidades = Unidades;       
            panel.VerticalAlignment = VerticalAlignment.Stretch;
            panel.HorizontalAlignment = HorizontalAlignment.Stretch;
            grid.Child = panel;
            panel.Cargar();

        }

        public void save()
        {
                try
                {
                    Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                    dlg.DefaultExt = ".emp";
                    dlg.Filter = "empresa files (.emp)|*.emp";

                    if (dlg.ShowDialog() == true)
                    {
                        string Fname = dlg.FileName;
                        empresa.invent = inventario;

                        FileStream stream = new FileStream(Fname, FileMode.Create);
                        BinaryFormatter formater = new BinaryFormatter();
                        formater.Serialize(stream, empresa);
                        formater.Serialize(stream, Unidades);

                        stream.Close();
                    }
                }
                catch (IOException)
                {
                }
            
        }

        public void open()
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".emp";
            dlg.Filter = "empresa files (.emp)|*.emp";

            Nullable<bool> result = dlg.ShowDialog();
            string filname = "";

            if (result == true)
            {
                filname = dlg.FileName;
                path_Empresa = filname;
            }

            try
            {
                FileStream s = new FileStream(filname, FileMode.Open);
                BinaryFormatter f = new BinaryFormatter();
                empresa = (Empresa)(f.Deserialize(s));
                Unidades = (List<Unidad>)(f.Deserialize(s));
                inventario = empresa.invent;

                CreateTree(empresa);
            }
            catch (Exception)
            {
            }
        }

        public void justSave()
        {
            try
            {
                if (path_Empresa != "")
                {
                    empresa.invent = inventario;
                    FileStream stream1 = new FileStream(path_Empresa, FileMode.Create);
                    BinaryFormatter formater1 = new BinaryFormatter();
                    formater1.Serialize(stream1, empresa);
                    formater1.Serialize(stream1, Unidades);
                    stream1.Close();

                    MessageBox.Show("Guardado exitoso", "EXITO AL GUARDAR", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                }
                else
                {
                    save();
                }
            }
            catch (IOException)
            {
            }
        }

        public void exportar()
        {
            try
            {
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.DefaultExt = "unit";
                dlg.Filter = "unidades files (.unit)|*.unit";

                if (dlg.ShowDialog() == true)
                {
                    string Fname = dlg.FileName;

                    FileStream stream = new FileStream(Fname, FileMode.Create);
                    BinaryFormatter formater = new BinaryFormatter();
                    formater.Serialize(stream, Unidades);

                    stream.Close();
                }
            }
            catch (IOException)
            {
            }
        }

        public void importar()
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".unit";
            dlg.Filter = "unidades files (.unit)|*.unit";

            Nullable<bool> result = dlg.ShowDialog();
            string filname = "";

            if (result == true)
            {
                filname = dlg.FileName;
            }

            try
            {
                FileStream s = new FileStream(filname, FileMode.Open);
                BinaryFormatter f = new BinaryFormatter();
                Unidades.AddRange((List<Unidad>)(f.Deserialize(s)));
                MessageBox.Show("Importación correcta de unidades, recuerde guardar los cambios!","ÉXITO",MessageBoxButton.OK,MessageBoxImage.Asterisk);
                //CreateTree(empresa);
            }
            catch (Exception)
            {
            }

        }

        private void itemGuardar_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            justSave();
        }

        private void itemGuardarComo_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            save();
        }

        private void itemExportar_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            exportar();
        }

        private void itemImportarU_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            importar();
        }

        private void itemSalir_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.Close();
        }

        private void itemAbrir_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            open();
        }

        private void arbol_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            Panel_Servicio panel = new Panel_Servicio();
            TreeViewItem servicio = (TreeViewItem)arbol.SelectedItem;
            panel.Load((Servicio)servicio.Tag);
            panel.VerticalAlignment = VerticalAlignment.Stretch;
            panel.HorizontalAlignment = HorizontalAlignment.Stretch;
            grid.Child = panel;
           
        }
    }
}
